<template>
  <div class="app-container">
    <div class="top-center" style="margin-bottom: 20px">
      <div class="item">
        <el-button icon="el-icon-arrow-left" class="back" @click="$router.back()"></el-button>
      </div>

      <div class="item">
        <el-input v-model="title" disabled style="width: 400px"></el-input>
      </div>

      <div class="item">
        <el-button
          style="background: #00bfd6; color: #ffffff"
          @click="loadExcel"
          :loading="downloadLoading"
        >导出</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      border
      element-loading-text="Loading"
      max-height="800"
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="cover" label="缩略图" width="150">
        <template slot-scope="scope">
          <img
            :src="scope.row.cover"
            alt
            style="width: 120px; height: 80px; object-fit: cover; margin: 10px 0"
          />
        </template>
      </el-table-column>
      <el-table-column prop="work_name" label="作品名称" width="220"></el-table-column>
      <el-table-column prop="username" label="作者ID" width="220"></el-table-column>
      <el-table-column prop="work_link" label="作品链接" width="300"></el-table-column>

      <el-table-column label="一审评委" class-name="vote-count" v-if="level == 0" min-width="180">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.teachers" :key="index" class="scopebox">{{ item }}</div>
        </template>
      </el-table-column>
      <el-table-column label="一审票数" class-name="vote-count" v-if="level == 0" min-width="180">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.status_list"
            :key="index"
            class="scopebox"
          >{{ (item == 1 ?"入围":"淘汰")}}</div>
        </template>
      </el-table-column>
      <el-table-column label="二审评委" class-name="vote-count" v-if="level == 1" width="140">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="二审星数" class-name="vote-count" v-if="level == 1" width="140">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.stars }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="startAll" label="二审总星数" v-if="level == 1" width="140"></el-table-column>
      <el-table-column label="三审评委" class-name="vote-count" width="140" v-if="level == 2">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创新性" class-name="vote-count" width="80" v-if="level == 2">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.scores[0] }}</div>
        </template>
      </el-table-column>
      <el-table-column label="品牌性" class-name="vote-count" width="80" v-if="level == 2">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.scores[1] }}</div>
        </template>
      </el-table-column>
      <el-table-column label="美观性" class-name="vote-count" width="80" v-if="level == 2">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.scores[2] }}</div>
        </template>
      </el-table-column>
      <el-table-column label="总分" class-name="vote-count" width="80" v-if="level == 2">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.totalScore }}</div>
        </template>
      </el-table-column>
      <el-table-column label="平均分" v-if="level == 2" width="80">
        <template slot-scope="scope">
          {{
          scope.row.averageScore.toFixed(2)
          }}
        </template>
      </el-table-column>
      <el-table-column label="星级推荐" class-name="vote-count" width="80" v-if="level == 2">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.teachers" :key="index" class="scopebox">
            <img
              src="@/assets/icons/star.png"
              alt
              v-if="item.collect == 1"
              style="width:16px; height:16px;display:block"
            />
            <span v-else>{{item.collect}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="findStatus" label="一审状态" v-if="level == 0" min-width="180"></el-table-column>
      <el-table-column
        :label="reviewLabel"
        class-name="vote-count"
        min-width="300"
        v-if="level == 1 || level == 2"
      >
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.teachers"
            :key="index"
            class="scopebox"
          >{{ item.comment }}</div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 40px 0">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="searchValue.page"
        :limit.sync="searchValue.limit"
        @pagination="fetchData"
      />
    </div>
  </div>
</template>

<script>
import {
  getWorksExport_03,
  getWorksExport_02,
  getWorksExport_01,
  getReviewThird,
  getReviewSecondary,
  getReviewFirst,
  getDownload
} from "@/api/works";
import axios from "axios";
export default {
  name: "Detail",

  data() {
    return {
      filter: {
        activity_id: null
      },
      searchValue: {
        activity_id: null,
        page: 1,
        limit: 10
      },
      total: 0,
      title: "",
      level: 1,
      tableData: [],
      sumOfStatusList: null,
      sortedScore: [],
      trimmedScores: [],
      downloadUrl: null,
      downloadLoading: false
    };
  },
  computed: {
    reviewLabel() {
      return this.level === 1 ? "二审评语" : "三审评语";
    }
  },
  mounted() {},
  created() {
    // 在组件创建时获取参数
    this.searchValue.activity_id = this.$route.query.activity_id;
    this.filter.activity_id = this.$route.query.activity_id;
    this.title = this.$route.query.title;
    this.level = this.$route.query.level;
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      if (this.level == 0) {
        let params = Object.assign({}, this.searchValue);
        getReviewFirst(params).then(response => {
          response.list.forEach(item => {
            if (item.teachers) {
              item.teachers = item.teachers.split(",");
            } else {
              item.teachers = [];
            }
            if (item.status_list) {
              item.status_list = item.status_list.split(",");

              const numArray = item.status_list.map(Number);

              // 计算数组中所有数值的总和
              this.sumOfStatusList = numArray.reduce(
                (acc, curr) => acc + curr,
                0
              );
              if (item.votes) {
                if (this.sumOfStatusList - item.votes > 0) {
                  item.findStatus = "入围";
                } else {
                  item.findStatus = "淘汰";
                }
              }
            } else {
              item.status_list = [];
            }
          });
          this.tableData = response.list;
          this.total = response.total;
          this.listLoading = false;
        });
      } else if (this.level == 1) {
        let params = Object.assign({}, this.searchValue);
        getReviewSecondary(params).then(response => {
          response.list.forEach(item => {
            if (item.teachers) {
              item.teachers = item.teachers.split(",");
            } else {
              item.teachers = [];
            }
            if (item.stars) {
              item.stars = item.stars.split(",");
              item.teachers = item.teachers.map(teacher => ({
                name: teacher,
                stars: "",
                comment: "-"
              }));
              // 将 status_list 的值逐个添加到 teachers 数组对应的下标数组里
              item.stars.forEach((stars, index) => {
                if (index < item.teachers.length) {
                  item.teachers[index].stars = Number(stars);
                }
              });
              const numArray = item.stars.map(Number);

              // 计算数组中所有数值的总和
              item.startAll = numArray.reduce((acc, curr) => acc + curr, 0);
            } else {
              item.stars = [];
            }

            if (item.comments) {
              item.comments = item.comments.split("#");
              item.comments.forEach((comment, index) => {
                if (index < item.teachers.length) {
                  item.teachers[index].comment = comment || "-";
                }
              });
            } else {
              item.comments = [];
            }
          });
          this.tableData = response.list;
          this.total = response.total;
          // console.log(this.tableData);
          this.listLoading = false;
        });
      } else if (this.level == 2) {
        let params = Object.assign({}, this.searchValue);
        getReviewThird(params).then(response => {
          response.list.forEach(item => {
            if (item.teachers) {
              item.teachers = item.teachers.split(",");
            } else {
              item.teachers = [];
            }
            if (item.scores_) {
              let scoreArr = item.scores_.split("#");

              item.teachers = item.teachers.map(teacher => ({
                name: teacher,
                scores: "-",
                comment: "-",
                collect: "-",
                totalScore: "-",
                averageScore: ""
              }));
              scoreArr.forEach((scores, index) => {
                if (index < item.teachers.length) {
                  scores = scores.split(",");
                  item.teachers[index].scores = scores.map(score =>
                    Number(score)
                  );
                  item.teachers[index].totalScore = item.teachers[
                    index
                  ].scores.reduce(
                    (accumulator, currentValue) => accumulator + currentValue,
                    0
                  );
                  item.teachers[index].averageScore =
                    item.teachers[index].scores.length > 0
                      ? item.teachers[index].totalScore /
                        item.teachers[index].scores.length
                      : 0;
                }
              });
            } else {
              item.scores_ = [];
            }

            if (item.comments) {
              item.comments = item.comments.split("#");
              item.comments.forEach((comment, index) => {
                if (index < item.teachers.length) {
                  item.teachers[index].comment = comment;
                }
              });
            } else {
              item.comments = [];
            }
            if (item.collect) {
              item.collect = item.collect.split(",");
              item.collect.forEach((collect, index) => {
                if (index < item.teachers.length) {
                  item.teachers[index].collect = collect;
                }
              });
            } else {
              item.collect = [];
            }

            item.teachers.forEach(te => {
              this.sortedScore.push(te.totalScore);
            });
            this.sortedScore = [...this.sortedScore].sort((a, b) => a - b);
            this.trimmedScores = this.sortedScore.slice(1, -1);
            item.averageScore =
              this.trimmedScores.length > 0
                ? this.trimmedScores.reduce((acc, curr) => acc + curr, 0) /
                  this.trimmedScores.length
                : 0;
            this.sortedScore = [];
          });
          this.tableData = response.list;
          this.total = response.total;
          console.log(this.tableData);
          this.listLoading = false;
        });
      }
    },
    async loadExcel() {
      this.downloadLoading = true;
      this.$message("正在导出，请稍等...");
      const params = { ...this.searchValue };
      const exportFunctions = [
        getWorksExport_01,
        getWorksExport_02,
        getWorksExport_03
      ];
      const exportFunction = exportFunctions[this.level];

      if (!exportFunction) {
        console.warn(`Invalid level: ${this.level}`);
        return false;
      }

      try {
        while (true) {
          const res = await exportFunction(params);

          if (res.code == 0 && res.row && res.no) {
            // 更新参数以获取下一页数据
            Object.assign(params, {
              no: res.no,
              row: res.row,
              page: params.page + 1
            });
          } else if (res.code == 2 && res.data) {
            // 文件信息返回，开始下载
            await this.downloadFileFromServer(res.data);
            break; // 下载完成，退出循环
          } else {
            // 没有更多数据或其他情况
            break;
          }
        }
        return true; // 成功完成导出
      } catch (error) {
        console.error("Error during export:", error);
        return false;
      } finally {
        this.downloadLoading = false;
      }
    },

    async downloadFileFromServer(fileName) {
      const url = `${process.env.VUE_APP_BASE_API}/api/works/download?name=${fileName}`;
      console.log(url);
      const headers = { "X-token": ` ${this.$store.getters.token || ""}` };

      try {
        const response = await axios.get(url, {
          headers,
          responseType: "blob"
        });

        // 创建 Blob 并触发下载
        const blob = new Blob([response.data], {
          type: response.headers["content-type"] || "application/octet-stream"
        });
        const downloadUrl = URL.createObjectURL(blob);
        const link = document.createElement("a");

        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(downloadUrl);

        // 可选：提示用户文件正在下载
        // alert('文件正在下载，请稍候...');
        this.$message.success("导出成功");
      } catch (error) {
        console.error("Error downloading:", error);
        alert("导出失败，请重试！");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  width: 100%;
  overflow: hidden;
}
.top-center {
  width: 100%;
  display: flex;
  align-items: center;
  .item {
    width: auto;
    margin-right: 20px;
  }
}

.back {
  font-weight: bold;
  font-size: 20px;
  padding: 10px 12px;
  color: #0cc3d8;
}
::v-deep .el-table.ch th.is-leaf {
  border-bottom: none !important;
}
::v-deep .el-table.ch {
  border: none;
  overflow: hidden;
  & > .el-table__header-wrapper,
  & > .el-table__body-wrapper {
    border: none;
  }
  .el-table__header tr,
  .el-table__body tr {
    border: none;
  }
  .el-table__header th,
  .el-table__body td {
    box-sizing: border-box;
    border-right: none;
    padding: 12px 0;
  }
}
::v-deep .el-table__header th.vote-count {
  padding-left: 10px;
  padding-right: 10px;
}
// 新增样式来设置 "一审票数" 列下的 cell 的 padding 为 0
::v-deep .vote-count .cell {
  box-sizing: border-box;
  padding: 0;
}
::v-deep .el-table__body tr.current-row > td {
  background: none;
}
::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background: none;
}
::v-deep .el-table td,
.el-table th {
  padding: 0;
}
::v-deep .el-table::before {
  height: 0px !important;
}
.scopebox {
  padding: 24px 10px;
  border-bottom: 1px solid #ebeef5;
}
.scopebox:last-child {
  border-bottom: none;
}
::v-deep .el-table .cell {
  line-height: 16px !important;
}
</style>
